import axios from 'axios'
import config from '../config/index'
import { Toast,Dialog } from 'vant';
class Http {
  
  static instance;

  // 单例模式
  static getInstance() {
    if (this.instance instanceof this) {
      return this.instance;
    } else {
      this.instance = new this;
      return this.instance;
    }
  }

  constructor() {
    this.SetBaseUrl();
    this.interceptors();
  }

  async get (url, params = {}, header = {}) {
    return await axios.get(url, { 
      params: params,
      headers: Object.assign(
        header,
        {
          Authorization: localStorage.getItem("token")
        }
      )
    })
  }

  async post (url, params = {}, header = {}) {
    return await axios.post(url, params, {
      headers: Object.assign(
        header,
        {
          Authorization: localStorage.getItem("token")
        }
      )
    })
  }

  interceptors() {
    /**
     * 请求拦截器
     */
    axios.interceptors.request.use(function (config) {
      return config;
    }, function (error) {
      // 对请求错误做些什么
      console.log(11);
      return Promise.reject(error);
    });

    /**
     * 响应拦截器 
     * 在这里处理返回数据的状态码
     */
    axios.interceptors.response.use(async (response) => {
      // 对响应数据做点什么
      return response; 
    }, function (error) {
      // 对响应错误做点什么
      let a= new Promise.reject(error)
      let p = new Promise((resolve, reject) => {
        //做一些异步操作
        setTimeout(() => {
            console.log('执行完成');
            resolve(error);
        }, 2000);
      });
      console.log(a);
      a.then((result) => {
        console.log("result", result);
      })
      let errora = 2
      return Promise.reject(error),errora;
    });
  }
  /**
   * 设置请求基地址
   */
  SetBaseUrl() {
    axios.defaults.baseURL = config.check();
  }

}

export default Http
